package com.atguigu.smsservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.smsservice.service.Smsservice;
import com.atguigu.smsservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(description = "短信发送")
@RestController
@RequestMapping("/edusms/send")
//@CrossOrigin
public class SmsController {
    @Autowired
    private Smsservice smsservice;

    @Autowired
    private RedisTemplate<String,String>redisTemplate;

    @ApiOperation(value = "发送验证码")
    @GetMapping("/sendCode/{phone}")
    public R sendCode(@PathVariable String phone){
        //1.访问redis，根据手机号获取验证码
        String rPhone = redisTemplate.opsForValue().get(phone);
        //2.判断有验证码，直接返回
        if(rPhone!=null){
            return R.ok();
        }
        //3.没有验证码，生成验证码
        String code = RandomUtil.getFourBitRandom();//四位的验证码
        //4.封装验证码，调用接口将map传过去
        Map<String,String>map=new HashMap<>();
        map.put("code",code);
        //5.发送验证码，获取返回值
        boolean isSend=smsservice.sendCode(phone,map);
        //6.发送成功，把验证码存入redis，设定时效
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else{
            return R.error().message("发送信息失败");
        }
    }
}
